import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter_09_game/config/app_color.dart';

class CountdownProgressPainter extends CustomPainter {
  final double progress; // 0.0 ~ 1.0
  final Color startColor;
  final Color endColor;
  final double strokeWidth;

  CountdownProgressPainter({
    required this.progress,
    this.startColor = AppColor.safetyScoreGradientMid,
    this.endColor = AppColor.primary,
    this.strokeWidth = 2,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final p = progress.clamp(0.0, 1.0);

    // 进度极小就不画，避免圆头抖动
    if (p <= 0.001) return;
    // AppColor
    final center = size.center(Offset.zero);
    final radius = size.shortestSide / 2;
    final rect = Rect.fromCircle(center: center, radius: radius);

    // 从顶部开始（-pi/2），顺时针 sweep
    const startAngle = -math.pi / 2;
    final sweepAngle = p * 2 * math.pi;

    // 关键：通过 stops 把渐变限制在 [0, progress] 区间，
    // 并把渐变整体旋转到顶部（-pi/2）
    final gradient = SweepGradient(
      startAngle: 0.0,
      endAngle: 2 * math.pi,
      colors: [
        startColor,
        endColor,

      ],
      stops: [
        0.0,
        p, // 渐变在 progress 处结束
      ],
      tileMode: TileMode.clamp,
      transform: const GradientRotation(-math.pi / 2), // 顶部起始
    );

    final paint = Paint()
      ..shader = gradient.createShader(rect)
      ..style = PaintingStyle.stroke
      ..strokeWidth = strokeWidth
      ..strokeCap = StrokeCap.butt;

    // 画弧：只渲染 0~progress 这一段
    canvas.drawArc(
      rect,
      startAngle,
      sweepAngle + 1e-6, // 避免某些平台收尾接缝
      false,
      paint,
    );
  }

  @override
  bool shouldRepaint(covariant CountdownProgressPainter old) {
    return old.progress != progress ||
        old.startColor != startColor ||
        old.endColor != endColor ||
        old.strokeWidth != strokeWidth;
  }
}
